package com.moyq5.wifi.joystick;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.moyq5.wifi.joystick.fragment.JoystickFragment;

import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class MainActivity extends ConsoleActivityAbstract {
    private static final Console console = ConsoleFactory.get(MainActivity.class);

    private BroadcastReceiver receiver;

    private IntentFilter intentFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        receiver = new WifiP2pServerReceiver(manager, channel, this);

        intentFilter = new IntentFilter();
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_DISCOVERY_CHANGED_ACTION);

        createP2pGroup();

        JoystickFragment fragment = new JoystickFragment();
        fragment.setConsole(console);

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.disallowAddToBackStack();
        fragmentTransaction.replace(R.id.controller_container, fragment);
        fragmentTransaction.commitNowAllowingStateLoss();
    }

    @Override
    int layoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, intentFilter);

    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (1 == requestCode) {
            if (grantResults.length > 0 && grantResults[0] == PERMISSION_GRANTED) {
                console.error("权限不足：%s", ACCESS_FINE_LOCATION);
            } else {
                console.info("授权通过：%s", ACCESS_FINE_LOCATION);
                createP2pGroup();
            }
        }
    }

    private void createP2pGroup() {
        if (checkSelfPermission(ACCESS_FINE_LOCATION) != PERMISSION_GRANTED) {
            requestPermissions(new String[]{ACCESS_FINE_LOCATION}, 1);
            return;
        }
        //WifiP2pConfig.Builder builder = new WifiP2pConfig.Builder();
                //.setNetworkName("DIRECT-moyq5");
        //Parcel parcel = Parcel.obtain();
        //parcel.
        //WifiP2pConfig config = WifiP2pConfig.CREATOR.createFromParcel()
        manager.createGroup(channel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                console.info("P2P 群组创建，成功");
            }

            @Override
            public void onFailure(int reason) {
                console.error("P2P 群组创建，失败：%s", reason);
            }
        });
        discoverPeers();
    }

    @SuppressLint("MissingPermission")
    private void discoverPeers() {
        console.debug("P2P 启动发现...");
        manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                console.info("P2P 启动发现，成功");
            }

            @Override
            public void onFailure(int reason) {
                console.info("P2P 启动发现，失败：%s", reason);
                ThreadKit.execute(() -> {
                    try {
                        Thread.sleep(3000);
                        discoverPeers();
                    } catch (InterruptedException ignored) {

                    }
                });
            }
        });
    }
}